package com.medical.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.mapper.DeptMapper;
import com.medical.model.entity.Dept;
import com.medical.model.ro.DeptRo;
import com.medical.service.DeptService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TISNIW
 * @version 1.0
 * @desc
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
    @Override
    public List<DeptRo> buildDeptTree(List<Dept> depts) {
        // 先将所有部门放入 map，方便后续查找父节点
        Map<Long, DeptRo> deptRoMap = new HashMap<>();

        // 将 Dept 转换为 DeptRo，并放入 map
        List<DeptRo> deptRoList = depts.stream()
                .map(dept -> DeptRo.builder()
                        .id(dept.getId())
                        .name(dept.getName())
                        .parentId(dept.getParentId())
                        .description(dept.getDescription())
                        .createdAt(dept.getCreatedAt())
                        .updatedAt(dept.getUpdatedAt())
                        .children(new ArrayList<>()) // 初始化 children
                        .build())
                .toList();
        deptRoMap.putAll(deptRoList.stream().collect(Collectors.toMap(DeptRo::getId, d -> d)));

        // 构建树
        List<DeptRo> rootNodes = new ArrayList<>();

        for (DeptRo deptRo : deptRoList) {
            Long parentId = deptRo.getParentId();
            if (parentId == null || parentId == 0) {
                rootNodes.add(deptRo);
            } else {
                DeptRo parent = deptRoMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(deptRo);
                }
            }
        }

        return rootNodes;
    }
}